﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;

namespace Hands.CSRF.Defense
{
    public class DefenseModule : IHttpModule
    {
        #region IHttpModule 成员

        public void Dispose()
        {
            // no op for this method
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += beginRequest;
        }

        private void beginRequest(object sender, EventArgs e)
        {
            HttpContext context = (HttpContext)sender;
            HttpCookie cookie = context.Request.Cookies[CookieHandler.CookieName];
            if (cookie != null)
            {
                if (CookieHandler.isLegal(cookie.Value))
                {
                    context.Request.Cookies.Remove(CookieHandler.CookieName);
                    context.Request.Cookies.Add(CookieHandler.create(context.Request.Url.Host));
                }
                else
                {
                    context.Response.Write("亲~您的身份不合法哦~是不是禁用了cookie~或者说您不是人类呢~");
                }
            }
            else
            {
                context.Response.Write("亲~您的身份不合法哦~是不是禁用了cookie~或者说您不是人类呢~");
            }
        }

        #endregion
    }
}
